package org.soulraven.games.memory.ui.config.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.JOptionPane;

import org.soulraven.games.memory.engine.MemoryEngine;
import org.soulraven.games.memory.engine.controller.Controller;
import org.soulraven.games.memory.model.Game;
import org.soulraven.games.memory.model.GameDifficulty;
import org.soulraven.games.memory.model.Player;
import org.soulraven.games.memory.ui.config.ConfigFrame;
import org.soulraven.games.memory.ui.config.ConfigPanel;
import org.soulraven.games.memory.util.MessageUtil;

public class ConfigController extends Controller {

	public static final String OK_BUTTON = "OK_BUTTON";
	public static final String CANCEL_BUTTON = "CANCEL_BUTTON";

	private ConfigFrame frame;

	public ConfigController(final ConfigFrame frame) {
		super();
		this.frame = frame;
		getResolvers().put(OK_BUTTON, new OkActionResolver());
		getResolvers().put(CANCEL_BUTTON, new CancelActionResolver());
	}
	
	@Override
	public void windowClosing(WindowEvent e) {
		onExit();
	}

	@Override
	public void onExit() {
		String message = MessageUtil.getMessage("confirmonexit");
		String title = MessageUtil.getMessage("exit");
		int dialogOption = JOptionPane.showConfirmDialog(
				frame, message, title,
				JOptionPane.YES_NO_OPTION,
				JOptionPane.QUESTION_MESSAGE);
		if (JOptionPane.YES_OPTION == dialogOption) {
			System.exit(0);
		}
	}

	private void onConfigFinished(final Game game, final List<Player> players) {
		final MemoryEngine engine = game.getMode().getEngine();
		frame.dispose();
		engine.start(game, players);
	}

	private class OkActionResolver implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			final ConfigPanel currentPanel = frame.getCurrentPanel();
			if (currentPanel.isDataEntered()) {
				// TODO BUILD WHEN OTHER DIFFICULTIES BE READY
				final Game game = new Game(GameDifficulty.EASY,
						currentPanel.getGameMode());
				onConfigFinished(game, currentPanel.getPlayers());
			} else {
				currentPanel.showWarning(frame);
			}
		}
	}

	private class CancelActionResolver implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			onExit();
		}
	}
}
